<template>
	<view>
		<u-sticky>
			<u-search @search="search" v-model="keyword" animation margin="0 32rpx" :showAction="false"></u-search>
		</u-sticky>
		<view @click="search(keyword)" class="px-[32px] py-[10px] text-[14px] text-[#666666]" v-if="!!keyword.trim()">搜索"{{keyword}}"</view>
		<view v-if="!keyword && history.length > 0" class="p-[16px]">
			<view class="flex flex-row justify-between items-center">
				<u-text text="搜索历史" bold></u-text>
				<u-icon name="trash" color="#333333" @click="del()"></u-icon>
			</view>
			<u-tag @click="search(item)" class="mr-[10px] mt-[10px]" v-for="(item,index) in history" :key="index" :text="item" shape="circle" color="#333333" bgColor="#EDEDED" borderColor="#EDEDED"></u-tag>
		</view>
	</view>
</template>

<script setup>
	import {ref, unref} from "vue";
	import * as uniapp from "@dcloudio/uni-app";
	
	const keyword = ref('');
	const history = ref([]);
	
	uniapp.onLoad(() => {
		uni.getStorage({
			key:'search',
			success(res) {
				history.value = res.data ? JSON.parse(res.data) : []
			}
		})
	})
	
	const search = e => {
		if(!e){
			uni.showToast({
				icon:'none',
				title:'请输入关键词'
			})
			return
		}
		if(!unref(history).some(i => i===e)) {
			history.value.push(e)
			uni.setStorage({
				data:JSON.stringify(unref(history)),
				key:'search'
			})
		}
		keyword.value = ''
		console.log('要跳转新的页面')
		uni.navigateTo({
			url:`/pages/searchResult/searchResult?keyword=${e}`
		})
	}
	
	const del = () => {
		uni.showModal({
			content:'要删除所有搜索记录吗？',
			success(res) {
				if(res.confirm) {
					history.value = []
					uni.removeStorage({
						key:'search'
					})
				}
			}
		})
	}
</script>

<style>

</style>
